var http = require('http');
var fs = require('fs');
var ejs = require('ejs');
var url = require('url');
var socketio = require('socket.io');

var constants = require('./constants.js');
var messenger = require('./messenger.js');
var notification = require('./notification/notification.js');

/*
 * Web Server Configuration
 */
var server = http.createServer();

server.on('request', function(request, response) {
	var query = url.parse(request.url, true).query;
	console.log('query: ' + query);
	
	fs.readFile('./resources/messenger-main.html', function(error, data) {
		response.writeHead(200, {'Content-Type': 'text/html'});
		response.end(data);
	});
});

server.listen(7778, function() {
	console.log('Server running at localhost:7778');
});

var io = socketio.listen(server);

io.sockets.on('connection', function(socket) {
	messenger.initialize(io, socket);
	
	socket.on('notificationList', function() {
		socket.get('name', function(error, name) {
			notification.getNotifications(name, function(notifications) {
				socket.emit('notificationList', notifications);
			});
		});
	});
});

notification.addListener('post', function(data) {
	console.log('talkaside post: ' + JSON.stringify(data));
	io.sockets['in'](data.targets).emit('notification', data.cell);
});